<template>
  <div>
    <!-- 头部 -->
    <a-card class="headers">
      型号搜索：
      <a-input v-model:value="name" placeholder="请输入" style="width: 200px" />
      <a-button type="primary" style="margin-left: 10px" @click="getdata()">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
    </a-card>
    <!-- 表格 -->
    <a-card>
      <a-button type="primary" style="margin-bottom: 10px" @click="showModal">
        <PlusCircleOutlined />
        新建
      </a-button>
      <a-table :columns="columns" :data-source="datas" :pagination="false">
        <template #action="{ record }">
          <a @click="put(record)">修改</a>
          <a-divider type="vertical" />
          <a style="color: red" @click="deldata(record._id)">删除</a>
        </template>
        <template #imgs="{ record }">
          <img :src="'http://127.0.0.1:3333/upload/'+record.imgs" alt="" srcset="" style="height: 50px;">
        </template>
      </a-table>
    </a-card>
    <!-- 分页 -->
    <div style="margin-top: 2.5vh; margin-bottom: 4vh" v-if="total > 10">
      <span style="color: #dbe5ef; font-size: 1rem; margin-left: 1rem">
        共{{ total }}条记录&nbsp;&nbsp;第 {{ page }}/{{
          Math.ceil(total / pageSize)
        }}页
      </span>
      <span style="float: right">
        <span style="margin-right: 3vw">
          <a-button
            style="background: #d5ddf8"
            :disabled="page <= 1"
            @click="onup"
            >上一页</a-button
          >
        </span>
        <span style="margin-right: 4vw">
          <a-button
            style="background: #d5ddf8"
            :disabled="page >= Math.ceil(total / pageSize)"
            @click="ondown"
            >下一页</a-button
          >
        </span>
      </span>
    </div>
    <!-- 添加 -->
    <a-modal
      v-model:visible="visible"
      title="新增策略"
      :footer="null"
      @cancel="notOk"
    >
      <a-form
        name="custom-validation"
        ref="formRef"
        :model="formState"
        :rules="rules"
        v-bind="layout"
        @finish="handleFinish"
        @finishFailed="handleFinishFailed"
      >
        <a-form-item label="型号名称" name="name">
          <a-input
            v-model:value="formState.name"
            placeholder="请输入"
            autocomplete="off"
            :maxlength="10"
          >
            <template #suffix>
              <span>{{ formState.name.length }}/10</span>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="型号编号" name="coding">
          <a-input
            v-model:value="formState.coding"
            placeholder="请输入（限制数字、字母、中划线、下划线）"
            autocomplete="off"
            :maxlength="15"
          >
            <template #suffix>
              <span>{{ formState.coding.length }}/15</span>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="货道行数" name="line">
          <a-input-number
            v-model:value="formState.line"
            placeholder="请输入"
            autocomplete="off"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="货到列数" name="number">
          <a-input-number
            v-model:value="formState.number"
            placeholder="请输入"
            autocomplete="off"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="货道容量" name="capacity">
          <a-input-number
            v-model:value="formState.capacity"
            placeholder="请输入"
            autocomplete="off"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="设备图片" name="imgs">
          <a-upload
            v-model:file-list="fileList"
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="http://127.0.0.1:3333/uploadfile"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" style="height: 110px;" />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 17, offset: 7 }">
          <a-button @click="resetForm">取消</a-button>
          <a-button type="primary" html-type="submit" style="margin-left: 50px"
            >确认</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 修改 -->
    <a-modal
      v-model:visible="visible2"
      title="修改策略"
      :footer="null"
      @cancel="notOk"
    >
      <a-form
        name="custom-validation"
        ref="formRef"
        :model="formState"
        :rules="rules"
        v-bind="layout"
        @finish="handleFinish2"
        @finishFailed="handleFinishFailed2"
      >
      <a-form-item label="型号名称" name="name">
          <a-input
            v-model:value="formState.name"
            placeholder="请输入"
            autocomplete="off"
            :maxlength="10"
          >
            <template #suffix>
              <span>{{ formState.name.length }}/10</span>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="型号编号" name="coding">
          <a-input
            v-model:value="formState.coding"
            placeholder="请输入（限制数字、字母、中划线、下划线）"
            autocomplete="off"
            :maxlength="15"
          >
            <template #suffix>
              <span>{{ formState.coding.length }}/15</span>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="货道行数" name="line">
          <a-input-number
            v-model:value="formState.line"
            placeholder="请输入"
            autocomplete="off"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="货到列数" name="number">
          <a-input-number
            v-model:value="formState.number"
            placeholder="请输入"
            autocomplete="off"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="货道容量" name="capacity">
          <a-input-number
            v-model:value="formState.capacity"
            placeholder="请输入"
            autocomplete="off"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="设备图片" name="imgs">
          <a-upload
            v-model:file-list="fileList"
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            action="http://127.0.0.1:3333/uploadfile"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="formState.imgs" :src="'http://127.0.0.1:3333/upload/'+formState.imgs" alt="avatar" style="height: 110px;" />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 17, offset: 7 }">
          <a-button @click="resetForm">取消</a-button>
          <a-button type="primary" html-type="submit" style="margin-left: 50px"
            >确认</a-button
          >
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import {
  SmileOutlined,
  DownOutlined,
  SearchOutlined,
  PlusCircleOutlined,
  PlusOutlined, 
  LoadingOutlined,
} from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import {
  getequipmentType,
  postequipmentType,
  delequipmentType,
  putequipmentType,
} from "@/api/peng/equipment";

// 头部输入
let name = ref("");
// 表单添加
const formRef = ref();
const { formState } = toRefs(
  reactive({
    formState: {
      name:'',
      coding:'',
      line:'',
      number:'',
      capacity:'',
      imgs:'',
    },
  })
);
// 修改框控制
const visible2 = ref(false);
// 表格配置
const columns = [
  {
    title: "序号",
    dataIndex: "_id",
    key: "_id",
  },
  {
    title: "型号名称",
    dataIndex: "name",
    key: "_id",
  },
  {
    title: "型号编码",
    dataIndex: "coding",
    key: "_id",
  },
  {
    title: "设备图片",
    key: "_id",
    slots: {
      customRender: "imgs",
    },
  },
  {
    title: "货道行",
    key: "_id",
    dataIndex: "line",
  },
  {
    title: "货道列",
    key: "_id",
    dataIndex: "number",
  },
  {
    title: "设备容量",
    key: "_id",
    dataIndex: "capacity",
  },
  {
    title: "操作",
    key: "action",
    slots: {
      customRender: "action",
    },
  },
];
// 表格内容数据
let datas = ref([]);
// 添加控制区
const visible = ref(false);
const showModal = () => {
  visible.value = true;
};
const notOk = () => {
  resetForm();
};
// 添加表单控制区
let checkAge = async (rule, value) => {
  if (!value) {
    return Promise.reject("请输入");
  }
  if (!Number.isInteger(value)) {
    return Promise.reject("请输入数字");
  }
};
let validatePass = async (rule, value) => {
  if (value === "") {
    return Promise.reject("请输入");
  }
};
let validateimgs = async (rule, value) => {
  if (value === "") {
    return Promise.reject("请选择图像");
  }
};
const rules = {
  name: [
    {
      required: true,
      validator: validatePass,
      trigger: "change",
    },
  ],
  coding: [
    {
      required: true,
      validator: validatePass,
      trigger: "change",
    },
  ],
  line: [
    {
      required: true,
      validator: checkAge,
      trigger: "change",
    },
  ],
  number: [
    {
      required: true,
      validator: checkAge,
      trigger: "change",
    },
  ],
  capacity: [
    {
      required: true,
      validator: checkAge,
      trigger: "change",
    },
  ],
  imgs: [
    {
      required: true,
      validator: validateimgs,
      trigger: "change",
    },
  ],
};
const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 20,
  },
};
// 确定添加验证成功 添加数据
const handleFinish = async (values) => {
  // console.log(values, formState.value);
  let { data } = await postequipmentType(values);
  {
    data.code === 200 ? message.success("添加成功") : message.error("添加失败");
  }
  getdata();
  resetForm();
};
// 确定添加验证失败
const handleFinishFailed = (errors) => {
  console.log("no");
};
// 重置关闭
const resetForm = () => {
  formState.value={
      name:'',
      coding:'',
      line:'',
      number:'',
      capacity:'',
      imgs:'',
    }
  formRef.value.resetFields();
  visible.value = false;
  visible2.value = false;
};
// 获取数据
const getdata = async () => {
  let { data } = await getequipmentType(name.value,page.value,pageSize.value);
  console.log(data);
  datas.value = data.data;
  total.value = data.count;
};
// 删除数据
const deldata = async (id) => {
  let { data } = await delequipmentType(id);
  console.log(data);
  {
    data.code === 200 ? message.success("删除成功") : message.error("删除失败");
  }
  getdata();
};
// 修改数据控制区
let _id = ref("");
const put = (val) => {
  // console.log(val);
  _id.value = val._id;
  formState.value = val;
  visible2.value = true;
};
// 确定修改验证成功 修改数据
const handleFinish2 = async (values) => {
  // console.log(values, formState.value);
  values._id = _id.value;
  let { data } = await putequipmentType(values);
  {
    data.code === 200 ? message.success("修改成功") : message.error("修改失败");
  }
  getdata();
  resetForm();
};
// 确定修改验证失败
const handleFinishFailed2 = (errors) => {
  console.log("no");
};
// 分页
 // 当前页
 let page = ref(1);
// 每页条数
 let pageSize = ref(10);
 // 总数量
 let total = ref(0);
 // 上一页
 const onup = () => {
 page.value--;
 getdata()
 };
 // 下一页
 const ondown = () => {
 page.value++;
 getdata()
 };
//  文件上传区
const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
let getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
const handleChange = info => {
  console.log(info.file.response.imgs);
  formState.value.imgs=info.file.response.imgs
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }

  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }

  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }

  return isJpgOrPng && isLt2M;
};
onMounted(() => {
  getdata();
});
</script>

<style scoped>
/* 文件上传 */
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>